﻿using System.Web.Mvc;
using System;

namespace MvcToolbox
{
    /// <summary>
    /// An Action Filter that attempts to format the result using a <see cref="MediaTypeViewResultFormatter"/>.
    /// If we request this page using our web browser we'll get the normal HTML result we expect.
    /// To return other formats we just need to set our accept headers to the appropriate media type. 
    /// So setting to application/json will return JSON and text/xml will return XML.
    /// </summary>
    /// <remarks>
    /// To add additional formatters use the <see cref="ViewResultFormatters.Formatters.Add(IViewResultFormatter)"/> method.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
    public class AutoFormatResultAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {

            var formatter = ViewResultFormatters.GetFormatter(filterContext);
            if (formatter != null)
            {
                var result = formatter.CreateResult(filterContext, filterContext.Result);

                if (result != null)
                    filterContext.Result = result;
            }
            base.OnActionExecuted(filterContext);
        }
    }
}
